<template>
  <div>
    <h1>排期页面</h1>
    <Banner
      v-if="films.length"
      :slides="films"
      :filmId="+route.params.filmId"
      @update:filmId="handleUpdateFilmId"
    />

    <Info v-if="activeFilm"  :film="activeFilm"/>

    <Tabs 
        :date="+route.params.date"
        v-if="activeFilm" 
        :showDate="activeFilm.showDate" 
        :schedules="schedules" 
        @update:date="handleUpdateDate"
    />


    <!-- <ul>
      <li v-for="item in films" :key="item.filmId">
        <RouterLink
          replace
          :to="{ name: 'schedule', params: { cinemaId: 10872, filmId: item.filmId } }"
        >
          {{ item.name }}
        </RouterLink>

      </li>
    </ul> -->
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, watchEffect } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Banner from './components/banner.vue'
import Info from './components/info.vue'
import Tabs from './components/tabs.vue'
import { getCinemaInfo, getCinemaFilmList, getCinemaScheduleList } from '@/api/modules/cinema'
import type { Cinema, Film, Schedule } from '@/api/interface'


let id : number | null = null
const route = useRoute()
const router = useRouter()
// 影院详情
const cinema = ref<Cinema.Item | null>(null)
// 电影列表
const films = ref<Film.Item[]>([])
// 排期列表
const schedules = ref<Schedule.Item[]>([])
// 当前电影
const activeFilm = computed(() => {
  let tmp = films.value.find((item) => item.filmId === +route.params.filmId)
  if (!tmp) {
    tmp = films.value[0]
  }
  return tmp
})

watchEffect(async () => {
  console.log('watchEffect')
  // 1. 获取 cinemaId filmId date
  let { cinemaId, filmId, date } = route.params as unknown as {
    cinemaId: number
    filmId: number
    date: number
  }

  

  if (!id) {
    // 2. 并行调用影院详情与影院电影列表接口
    const [{ cinema: aaaa }, { films: bbbb }] = await Promise.all([
      getCinemaInfo(cinemaId),
      getCinemaFilmList(cinemaId)
    ])
    // 3. 赋值
    id = cinemaId
    cinema.value = aaaa
    films.value = bbbb
    console.log('bbbb', bbbb)
  }

  //4.处理filmId与date
  if (!filmId) {
    filmId = films.value[0].filmId
  }
  if (!date) {
    date = films.value[0].showDate[0]
  }

  //5.获取 排期列表数据
  const { schedules: page } = await getCinemaScheduleList({ cinemaId, filmId, date })
  schedules.value = page
})

function handleUpdateFilmId(filmId: number) {
  console.log('handleUpdateFilmId')
  // 路由跳转
  router.replace({ name: 'schedule', params: { cinemaId: cinema.value?.cinemaId, filmId: filmId } })
}

function handleUpdateDate(date: number) {
  console.log('handleUpdateDate', date)

  // 路由跳转
  router.replace({
    name: 'schedule',
    params: { cinemaId: cinema.value?.cinemaId, filmId: activeFilm.value.filmId, date }
  })
}

</script>
